package org.huoran.sakamichi.main.netty.simpleTCP;

import org.apache.commons.lang3.StringUtils;
import org.jboss.netty.channel.*;


public class TCPServerHandler extends SimpleChannelUpstreamHandler  {
    private static final String CLOSE_FLAG = "exit";

    @Override
    public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) {
        String content = e.getMessage().toString();
        // client exit
        if(StringUtils.isNotEmpty(content) && content.equals(CLOSE_FLAG)){
            e.getChannel().write(CLOSE_FLAG);
            e.getChannel().close();
        }
        // client message
        else{
            System.out.println("from " + ctx.getChannel().getRemoteAddress() + " : " + content);
        }
    }

    @Override
    public void channelConnected(ChannelHandlerContext ctx, ChannelStateEvent e)
            throws Exception {
        System.out.println("get new client : " + ctx.getChannel().getRemoteAddress());
    }

        @Override
    public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) {
        e.getCause().printStackTrace();
        Channel ch = e.getChannel();
        ch.close();
    }
}